import pygame
from   pygame.locals import *

pygame.mixer.pre_init(22050,-16,2,2048)
pygame.init()


import factories

import display

from config import CONFIG

class MainLoop:
  def __init__(self):
    self.screen = pygame.display.set_mode((800,500),HWSURFACE|DOUBLEBUF,32)
    
    pygame.display.set_caption('Foxen - v0.0.0')
    
    self.factory = factories.GeneralFactory()
    self.level   = self.factory.load_level('test')
    self.player  = self.level.player
    
    self.controls = {'Left':False,'Right':False,'Run':False,
                     'Jump':False,'Close':False}
    
    self.status = 'Game'
    
    self.timer = pygame.time.Clock()
  
  def go(self):
    while True:
      self.timer.tick(30)
      
      self.step()
  
  def step(self):
    for event in pygame.event.get():
      if   event.type == QUIT:
        pygame.quit()
        exit()
      elif event.type == KEYDOWN:
        if event.key == K_r:
          if self.player.health == 2:
            self.player.health = 1
          elif self.player.health == 1:
            self.player.health = 2
        
        for ctrl_name in self.controls.keys():
          ctrl_keys = CONFIG['Controls']['Keyboard']
          
          if ctrl_keys[ctrl_name] == pygame.key.name(event.key):
            self.controls[ctrl_name] = True
      elif event.type == KEYUP:
        for ctrl_name in self.controls.keys():
          ctrl_keys = CONFIG['Controls']['Keyboard']
          
          if ctrl_keys[ctrl_name] == pygame.key.name(event.key):
            self.controls[ctrl_name] = False
    
    if self.controls['Close']:
      pygame.quit()
      exit()
    
    if self.status == 'Game':
      self.level.update(self.controls)
      
      display.draw_game_screen(self.screen,self.level)
      
      pygame.display.flip()

if __name__.lower() == '__main__':
  MainLoop().go()
